const express = require('express');
const cors = require('cors');

// 导入路由
const partnersRouter = require('./routes/partners');
const aboutRouter = require('./routes/about');
const servicesRouter = require('./routes/services');

const app = express();
const PORT = process.env.PORT || 3001;

// 中间件
app.use(cors({
  origin: true, // 开发环境允许所有来源
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  next();
});

// API路由
app.use('/api/partners', partnersRouter);
app.use('/api/about', aboutRouter);
app.use('/api/services', servicesRouter);

// 根路径
app.get('/', (req, res) => {
  res.json({
    message: '🐾 Pet Mall API Server 运行中',
    version: '1.0.0',
    endpoints: {
      'GET /api/partners': '获取所有合作伙伴',
      'GET /api/partners/:id': '获取单个合作伙伴',
      'POST /api/partners': '添加合作伙伴',
      'PUT /api/partners/:id': '更新合作伙伴',
      'DELETE /api/partners/:id': '删除合作伙伴'
    },
    queryParams: {
      'category': '按分类筛选 (food, care, accessories)',
      'status': '按状态筛选 (active, inactive)',
      'limit': '限制返回数量'
    }
  });
});

// 健康检查接口
app.get('/health', (req, res) => {
  res.json({
    status: 'OK',
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在',
    path: req.originalUrl
  });
});

// 错误处理中间件
app.use((error, req, res) => {
  console.error('服务器错误:', error);
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? error.message : undefined
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`
🚀 Pet Mall API Server 启动成功!
📍 服务地址: http://localhost:${PORT}
📖 API文档: http://localhost:${PORT}
🔍 健康检查: http://localhost:${PORT}/health
⏰ 启动时间: ${new Date().toLocaleString()}
  `);
});

module.exports = app;
